<template>
  <view class="container" v-if="fee && fee.orderFeeList">
    <settlementDetail v-for="(item, index) in fee.orderFeeList" :key="index" :item="item" />
    <ve-card type="blue" :fold="false">
      <template #title>
        结算总额：<text class="text-blue">{{ currentTotalObj.total }}元</text>
      </template>
      <view class="summary">
        <view class="summary-item">
          <view class="summary-title">
            <text>收款</text>
            <text>{{ currentTotalObj.collection }}元</text>
          </view>
          <view>
            <text>线上费用</text>
            <text>{{ currentTotalObj.collection_online }}元</text>
          </view>
          <view>
            <text>线下费用</text>
            <text>{{ currentTotalObj.collection_offline }}元</text>
          </view>
        </view>
        <view class="summary-item">
          <view class="summary-title">
            <text>付款</text>
            <text>{{ currentTotalObj.pay }}元</text>
          </view>
          <view>
            <text>线上费用</text>
            <text>{{ currentTotalObj.pay_online }}元</text>
          </view>
          <view>
            <text>线下费用</text>
            <text>{{ currentTotalObj.pay_offline }}元</text>
          </view>
        </view>
      </view>
      <!-- 表单 -->
      <ve-form ref="veFormRef" :model="form" :rules="rules">
        <ve-form-item
          label="结算方式"
          required
          prop="paymentWay"
          labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
        >
          <ve-picker-inline
            v-model="form.paymentWay"
            placeholder="请选择"
            :range="paywayEnum"
            unit="arrowRight"
            @change="typeChange"
          ></ve-picker-inline>
        </ve-form-item>
        <template v-if="form.paymentWay">
          <ve-form-item
            v-if="form.paymentWay == 4"
            label="选择使用哪笔订单押金"
            labelPosition="top"
            labelTooltipContent="支持选择同一承租人下的芝麻免押押金、违章关联订单如果是线下支付的押金，使用其违章押金抵扣；芝麻免押使用的是租车押金&违章押金；芝麻免押的押金支持查看详情"
            required
            labelTooltipPosition="top"
            prop="deductionOrderId"
          >
            <view style="width: 100%">
              <remote-select
                slotStatus
                type="deductionOrder"
                v-model="form.deductionOrderId"
                placeholder="请选择"
                :outData="deductionOrderList"
                unit="arrowRight"
                @change="deductionOrderChange"
              >
                <template #remote-select>
                  <view class="deduction-order-select">
                    <view style="width: 100%; display: flex; align-items: center; margin-bottom: 8rpx">
                      <text v-if="form.orderNo">{{ form.orderNo }}</text>
                      <text class="placeholder" v-else>请选择订单</text>
                      <view class="remote-select_arrow">
                        <ve-icon name="arrow_right_0" size="32" :block="true" />
                      </view>
                    </view>
                    <text class="deduction-order-select-amount" v-if="form.availableAmount">{{ form.availableAmount }}</text>
                  </view>
                </template>
              </remote-select>
              <ve-button
                v-if="form.deductionOrderId && form.payType == 4"
                type="plain"
                size="mini"
                :customStyle="{ backgroundColor: '#F3F7FF' }"
                style="width: 100%; margin-top: 24rpx"
                @click="toDeductionOrderDetail"
              >
                查看押金详情
              </ve-button>
            </view>
          </ve-form-item>
          <ve-form-item v-if="form.paymentWay == -1" label="结算主体" required prop="account">
            <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
          </ve-form-item>
          <ve-form-item v-else label="结算账号" labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。">
            <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight"></ve-picker-inline>
          </ve-form-item>
          <ve-form-item v-if="form.paymentWay && form.paymentWay != -1" label="结算时间" required prop="paymentTime">
            <ve-date-picker v-model="form.paymentTime" title="时间"></ve-date-picker>
          </ve-form-item>
          <ve-form-item label="客户名称" required prop="customerName">
            <ve-input v-model="form.customerName" placeholder="请输入" :maxlength="20" />
          </ve-form-item>
          <ve-form-item label="客户结算账号">
            <ve-input v-model="form.customerAccount" placeholder="请输入" :maxlength="20" />
          </ve-form-item>
          <ve-form-item label="结算备注" :borderBottom="false" labelPosition="top">
            <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入备注" :maxlength="200" />
          </ve-form-item>
          <ve-form-item label="上传凭证" labelPosition="top">
            <ve-upload v-model="form.fileIdList" max-count="10"></ve-upload>
          </ve-form-item>
        </template>
      </ve-form>
    </ve-card>

    <view style="height: 280rpx">
      <ve-bottom-box>
        <ve-button type="primary" @click="beforeSubmitFn" style="width: 100%" :loading="okLoading">结算</ve-button>
      </ve-bottom-box>
    </view>
    <ve-modal title="提示" v-model="confirmVisible" @confirm="formSubmit">
      <view style="margin-bottom: 20px">结算费项中包含线上费用及线下费用，是否确认合并结算？</view>
    </ve-modal>
  </view>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/dict/detail'
  import { orderFeeToConfirm } from '@/api/order/sOrder'
  import useToast from '@/hooks/useToast'
  import useFormFold from '@/hooks/useFormFold'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import settlementDetail from './components/settlement-detail.vue'
  import { orderFeeConfirmFee, getDepositOrderList } from '@/api/asset/asset-fee'
  import { userStore } from '@/stores'
  import dayjs from 'dayjs'

  const userInfoStore = userStore()
  const okLoading = ref(false)

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['paymentTime', 'paymentWay', 'customerName', 'account', 'deductionOrderId'],
    },
  ])
  const veFormRef = ref()
  const costType = ref()
  const pagefrom = ref() //判断页面回退 expense详情页  mergeConfirm合并页
  const receiveAmount = ref(0)
  const paywayEnum = ref() //收付款方式
  const accountList = ref() //收付款账号
  const costName = ref() //收款or付款
  const idList = ref([])
  const fee = ref<any>()
  const form = ref<any>({})
  const disabledCostType = ref(false)
  const orderFeeList = ref<any>([])
  const shortOrderData = ref<any>({})
  const rules = ref<any>({
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    actualAmount: {
      required: true,
      message: '请输入',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  })
  // 计算当前输入金额
  const currentTotalObj = computed(() => {
    let total = 0, // 本次结算总额
      pay = 0, // 付款
      collection = 0, // 收款
      pay_online = 0, //付款线上支付
      pay_offline = 0, // 付款线下支付
      collection_online = 0, // 收款线上支付
      collection_offline = 0 //收款线下支付
    orderFeeList.value.map((it: any) => {
      // 付款=20 收款=10 线下费用：feeType == 1
      if (it.costType == 20) {
        pay += it.settlementAmount * 1000
        it.feeType == 1 ? (pay_offline += it.settlementAmount * 1000) : (pay_online += it.settlementAmount * 1000)
      } else {
        collection += it.settlementAmount * 1000
        it.feeType == 1 ? (collection_offline += it.settlementAmount * 1000) : (collection_online += it.settlementAmount * 1000)
      }
    })
    total = collection - pay
    // 收款及付款合并结算，结算金额变为负数时，需判断当前选择的结算方式是否满足
    getType(total >= 0 ? 10 : 20, fee.value.orderFeeList, total)
    return {
      total: total / 1000,
      pay: pay / 1000,
      collection: collection / 1000,
      pay_online: pay_online / 1000,
      pay_offline: pay_offline / 1000,
      collection_online: collection_online / 1000,
      collection_offline: collection_offline / 1000,
    }
  })

  // 处理押金默认选中本单
  const deductionOrderChange = (val: any, option: any) => {
    if (val) {
      const [prefix, content] = option.orderCode.split(/[()]/).filter(Boolean)
      form.value.orderNo = prefix
      form.value.availableAmount = content
      form.value.deductionOrderId = val
      form.value.orderCode = option.orderCode
      form.value.payType = option.payType
      form.value.deductionOrderType = option.orderType
    } else {
      form.value.orderNo = ''
      form.value.availableAmount = ''
      form.value.deductionOrderId = ''
      form.value.orderCode = ''
      form.value.payType = ''
      form.value.deductionOrderType = ''
    }
  }

  // 获取押金订单列表
  const deductionOrderList = ref<any>([])
  const handleDepositOrderList = () => {
    getDepositOrderList({
      memberId: shortOrderData.value.memberId,
      orderId: fee.value.orderId,
      orderType: shortOrderData.value.orderType,
      payTypeList: [4],
    }).then((res: any) => {
      deductionOrderList.value = res.result || []
    })
  }

  const getDetail = async () => {
    const res: any = await orderFeeToConfirm({ idList: idList.value })
    console.log('short getDetail: ', res.result)

    receiveAmount.value = Math.abs(res.result.receiveAmount) //合计（取绝对值）
    form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
    var datafee = res.result
    orderFeeList.value = datafee.orderFeeList
    shortOrderData.value = datafee.shortOrder
    // 嵌入展开收起open
    if (datafee.orderFeeList && datafee.orderFeeList.length > 0) {
      datafee.orderFeeList.forEach((item: any) => {
        item.tableOpen = false //控制单个费用 整个表的显示隐藏
        item.open = false //控制1级
        item.settlementAmount = item.waitPayAmount
        item.errorStatus = false
        if (item.feeDetailList && item.feeDetailList.length > 0) {
          item.feeDetailList.forEach((el: any) => {
            el.open = false //控制2级
            if (el.childrenList && el.childrenList.length > 0) {
              el.childrenList.forEach((pl: any) => {
                pl.open = false
              })
            }
          })
        }
      })
    }
    fee.value = datafee
    form.value.paymentTime = dayjs().format('YYYY-MM-DD HH:mm:ss') //默认时间
    form.value.customerName = res.result.shortOrder.memberName //默认客户
    costType.value = res.result.costType
    if (costType.value == 10) {
      costName.value = '收款'
    } else {
      costName.value = '付款'
    }
    // 押金抵扣为固定收付款方式
    if (res.result.payType != null) {
      disabledCostType.value = true
      form.value.paymentWay = res.result.payType.toString()
    }
    form.value.orderId = fee.value.orderFeeList[0]?.orderId
    // getType(costType.value, form.value.actualAmount)
    handleDepositOrderList()
  }
  // 1级
  const open1 = (index: number) => {
    fee.value.orderFeeList[index].open = !fee.value.orderFeeList[index].open //1级
    fee.value.orderFeeList[index].feeDetailList.forEach((item: any) => {
      item.open = true //2级
    })
  }
  // 2级
  const open2 = (index: number, elindex: any) => {
    fee.value.orderFeeList[index].feeDetailList.forEach((item: any, itemindex: any) => {
      if (itemindex == elindex) {
        item.open = !item.open
      }
    })
  }
  // 收付款类型（方式）
  const getType = (costType: any, orderFeeList = [], total: any) => {
    // 是否包含线下费用
    const is_offline = orderFeeList.every((item: any) => item.feeType == 1)
    console.log('is_offline', is_offline)

    const is_collection = orderFeeList.every((item: any) => item.costType == 10)
    console.log('is_collection', is_collection)

    // 是否包含租车押金和违章押金
    const is_contain_rent_violation = orderFeeList.some((item: any) => item.feeNameId == 12 || item.feeNameId == 13)
    console.log('is_contain_rent_violation', is_contain_rent_violation)

    let is_show_jialian = false
    if (orderFeeList.length == 1 && is_collection && total > 0) {
      is_show_jialian = true
    } else if (orderFeeList.length > 1) {
      if (is_collection && total > 0) {
        is_show_jialian = true
      } else if (!is_collection && total > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    getAccountByPageData({ type: costType == 10 ? 0 : 1 }).then((res: any) => {
      let newarr: any[] = []
      const data = res.result

      // 订单不显示押金抵扣和预授权
      newarr = data.filter((i: any) => i.way != '5')

      // costType: 10 收款 20 付款
      // i.type: 0 收款 1 付款 2收款&付款
      if (costType == 10) {
        newarr = newarr.filter((i: any) => i.type != '1')
      } else {
        newarr = newarr.filter((i: any) => i.type != '0')
      }
      // 未结金额为负数时，本次结算为付款，相反为收款
      if (total != 0) {
        newarr = newarr.filter((i: any) => (i.type != total < 0 ? '0' : '1'))
      }

      /**
       * 不显示嘉联聚合支付
       * enterpriseDetail.value.jialianEnabled: 0 未开通嘉联聚合支付
       * total: 收款金额小于等于0
       * is_offline: 不是线下费用时
       * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
       * is_contain_rent_violation: 是否包含租车押金和违章押金
       */
      if (enterpriseDetail.value.jialianEnabled == 0 || !is_show_jialian || !is_offline || is_contain_rent_violation) {
        newarr = newarr.filter((el) => el.way != '-1')
      }
      /**
       * 此处逻辑：
       * 金额大于等于0，接口返回收款的结算类型，小于0，接口返回付款的结算类型
       * 但是金额等于0的时候也不能显示押金扣款
       */
      if (total <= 0) {
        newarr = newarr.filter((el: any) => el.way != '4')
      }
      // 退款抵扣违约金仅在取消时，退款及违约金自动抵扣时使用，其他环节及费项不允许选择该收支方式
      newarr = newarr.filter((el) => el.way != '-2')

      const children = newarr.map((childItem) => {
        return {
          value: childItem.way,
          label: childItem.wayStr,
          type: childItem.type,
        }
      })
      paywayEnum.value = children
      // 如果下拉选项中不存在当前结算方式 => 清空
      if (!paywayEnum.value.find((it) => it.value == form.value.paymentWay)) form.value.paymentWay = ''
    })
  }
  // 账号
  const typeChange = (e: string | number) => {
    if (e == -1) {
      rules.value.account = {
        required: true,
        message: '请选择',
      }
    } else {
      delete rules.value.account
    }

    form.value.account = ''

    paywayEnum.value.forEach((el: any) => {
      if (el.value == e) {
        getAccountByWayAndType({ way: Number(el.value), type: costType.value == 10 ? 0 : 1 }).then((res: any) => {
          var children = res.result.map((childItem: any) => {
            return {
              value: childItem.id,
              label: form.value.paymentWay != -1 ? childItem.account + '_' + childItem.bank : childItem.bank,
            }
          })

          if (children.length == 1 && form.value.paymentWay == -1) {
            form.value.account = children[0].value
          }

          accountList.value = children
        })
      }
    })

    // 如果结算方式是押金抵扣
    if (e == 4) {
      rules.value.deductionOrderId = {
        required: true,
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (!value) return callback(new Error('请选择'))

          deductionOrderList.value.forEach((it: any) => {
            if (it.orderId == value) {
              if (it.availableDepositAmount < currentTotalObj.value.total) {
                callback(new Error('押金金额不足，请修改本次结算金额'))
              } else {
                callback()
              }
            }
          })
        },
      }

      if (deductionOrderList.value.length > 0 && deductionOrderList.value[0].orderCode.includes('本单')) {
        deductionOrderChange(deductionOrderList.value[0].orderId, deductionOrderList.value[0])
      }
    } else {
      form.value.orderNo = ''
      form.value.availableAmount = ''
      form.value.deductionOrderId = ''
      form.value.orderCode = ''
      delete rules.value.deductionOrderId
    }
  }
  // 存在线上线下费用时，弹窗提示
  const confirmVisible = ref(false)
  const beforeSubmitFn = () => {
    let settlementAmountErrorObj = fee.value.orderFeeList.find((it) => it.errorStatus == true)
    if (settlementAmountErrorObj) return uni.showToast({ title: settlementAmountErrorObj.errorMsg, icon: 'none' })
    // 判断是否同时存在线上及线下费用
    let costTypeArr = fee.value.orderFeeList.map((it) => it.feeType)
    confirmVisible.value = costTypeArr.includes(1) && costTypeArr.includes(2)
    if (confirmVisible.value) return
    formSubmit()
  }

  const toDeductionOrderDetail = () => {
    uni.navigateTo({
      url: `/pages/order/short-order/free-deposit-detail?orderId=${form.value.deductionOrderId}`,
    })
  }

  // 提交
  const formSubmit = () => {
    confirmVisible.value = false
    okLoading.value = true
    veFormRef.value.validate((valid: any, errors: any) => {
      if (valid) {
        const param = {
          ...form.value,
          orderId: fee.value.orderId,
          orderFeeList: orderFeeList.value.map((it) => {
            return {
              id: it.id,
              settlementAmount: it.settlementAmount,
            }
          }),
        }
        orderFeeConfirmFee(param)
          .then((res: any) => {
            okLoading.value = false
            if (res.code == 200) {
              okLoading.value = false
              if (form.value.paymentWay == -1) {
                const from =
                  pagefrom.value == 'mergeConfirm'
                    ? 'order/short-order/detail/mergeConfirmation'
                    : 'order/short-order/detail/confirmExpenses'
                uni.navigateTo({
                  url: `/pages/common/components/qrcode?id=${res.result}&from=${from}`,
                })
              } else {
                useToast({
                  title: '确认成功',
                }).then(() => {
                  setTimeout(() => {
                    if (pagefrom.value == 'orderList') {
                      useLoadDataAndHotUpdateNavigateBack()
                    }
                    if (pagefrom.value == 'expense') {
                      uni.navigateBack({ delta: 1 })
                      uni.$emit('operateSuccess')
                    }
                    if (pagefrom.value == 'mergeConfirm') {
                      uni.navigateBack({ delta: 2 })
                    }
                  }, 500)
                })
              }
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        okLoading.value = false
        console.log('验证失败', errors)
      }
    })
  }
  const showRemark = (text: string) => {
    uni.showModal({
      title: '备注',
      content: text,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      },
    })
  }
  const enterpriseDetail = ref<any>({})
  onLoad((options: any) => {
    if (options.idList) {
      idList.value = JSON.parse(options.idList)
      form.value.idList = idList.value
      getDetail()
    }
    if (options.pagefrom) {
      pagefrom.value = options.pagefrom
    }
    userInfoStore.setEpDetail(false).then((res) => {
      enterpriseDetail.value = res
    })
  })
</script>

<style lang="scss" scoped>
  page {
    background: #f7f8fa;
  }
  .container {
    padding: 24rpx;
  }
  .text-blue {
    color: #3072f6;
  }
  .summary {
    padding: 24rpx 0;
    display: flex;
    justify-content: space-between;
    &-item {
      width: 48%;
      background: #f7f8fa;
      padding: 24rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #191c27;
      view {
        display: flex;
        justify-content: space-between;
      }
    }
    &-title {
      font-weight: 600;
      font-size: 28rpx;
      color: #3072f6;
      margin-bottom: 8rpx;
    }
  }
  .viewports {
    background: #f7f8fa;
    display: flex;
    flex-direction: column;
    padding: 24rpx;
  }
  .line {
    width: 100%;
    background: #d8d8d8;
    height: 1rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin: 24rpx 0;
    .fee-table {
      width: 800rpx;
      .tlt {
        width: 100%;
        height: 88rpx;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-first {
        width: 100%;
        margin: 32rpx 0 16rpx;
        background: #ffffff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #191c27;
        font-size: 28rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-other {
        margin-left: 22rpx;
        .twice {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view {
            margin-top: 24rpx;
          }
          view:nth-child(1) {
            width: 296rpx;
            margin-left: 24rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
      }
    }
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }
  .deduction-order-select {
    width: 100%;
    font-size: 30rpx;
    font-weight: 400;
    color: #191c27;
    line-height: 44rpx;
  }

  .deduction-order-select-amount {
    color: #3072f6;
  }
  .placeholder {
    color: #8491a8;
  }
</style>
